package com.foxchen.fanjingmontainticket.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.foxchen.fanjingmontainticket.bean.TicketVO;
import com.foxchen.fanjingmontainticket.service.TicketBasicService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

import static com.foxchen.fanjingmontainticket.schedule.task.BuyTicketTask.OBJECT_MAPPER;

@Slf4j
@Service
public class TicketBasicServiceImpl implements TicketBasicService {
    private static final String LIST_TIME_API = "https://etrip.icbc.com.cn/api-trip/trip/productManage/queryDayTimeShareQuote/mw/2000001053?corpId=2000001053";
    private static final String LIST_PERSON_API = "https://etrip.icbc.com.cn/api-trip/generalContact?resortId=0&corpId=2000001053";

    @Override
    public String listAllTimeByDate(TicketVO ticketVO) {
        OkHttpClient client = new OkHttpClient();
        int recordId = ThreadLocalRandom.current().nextInt(1, 10001);
        String decodedPayload = """
                {
                     "corpId": "2000001053",
                     "prodId": "%s",
                     "recordId": "%s",
                     "buyDate": "%s",
                     "ticketCategory": "1",
                     "salesChannel": "1",
                     "remainTicket": "1"
                 }
                """.formatted(ticketVO.getProdId(),recordId,ticketVO.getDateStr());
        RequestBody body = RequestBody.Companion.create(decodedPayload.getBytes(StandardCharsets.UTF_8), MediaType.parse("application/json; charset=utf-8"));

        int length = decodedPayload.getBytes(StandardCharsets.UTF_8).length;
        Request request = new Request.Builder()
                .url(LIST_TIME_API)
                .post(body)
                .addHeader("content-length", length + "")
                .addHeader("accept", "application/json")
                .addHeader("method", "POST")
                .addHeader("x-trip-tag", "{\"gray\":\"V1.13.1000050.0.25040915513965\"}")
                .addHeader("authorization", "")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090c33) XWEB/11581 Flue")
                .addHeader("content-type", "application/json; charset=utf-8")
                .addHeader("origin", "https://etrip.icbc.com.cn")
                .addHeader("sec-fetch-site", "same-origin")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("referer", "https://etrip.icbc.com.cn/mobile/trip/tripmobile/Elife/index.html?corpId=2000001053")
                //.addHeader("accept-encoding", "gzip, deflate, br")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("cookie", ticketVO.getUser())
                .build();
        try (Response response = client.newCall(request).execute()) {
            if((response.code() == 0 || response.code() == 200) && response.body() != null){
                ResponseBody rspBody = response.body();
                Map<String, Object> objectMap = OBJECT_MAPPER.readValue(rspBody.bytes(), new TypeReference<>() {});
                log.info("========================url:{}",LIST_TIME_API);
                log.info("========================request:{}",decodedPayload);
                log.info("========================response:{}",objectMap);
                return OBJECT_MAPPER.writeValueAsString(objectMap);
            }
        } catch (Exception e) {
            log.error("execute error.",e);
        }

        return "";
    }

    @Override
    public String listPerson(TicketVO ticketVO) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(LIST_PERSON_API)
                .addHeader("accept", "application/json")
                .addHeader("method", "GET")
                .addHeader("x-trip-tag", "{\"gray\":\"V1.13.1000050.0.25040915513965\"}")
                .addHeader("authorization", "")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090c33) XWEB/11581 Flue")
                .addHeader("sec-fetch-site", "same-origin")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("referer", "https://etrip.icbc.com.cn/mobile/trip/tripmobile/Elife/index.html?corpId=2000001053&type=1")
                //.addHeader("accept-encoding", "gzip, deflate, br")
                .addHeader("accept-language", "zh-CN,zh;q=0.9")
                .addHeader("cookie", ticketVO.getUser())
                .build();


        try (Response response = client.newCall(request).execute()) {
            if((response.code() == 0 || response.code() == 200) && response.body() != null){
                ResponseBody rspBody = response.body();
                Map<String, Object> objectMap = OBJECT_MAPPER.readValue(rspBody.bytes(), new TypeReference<>() {});
                log.info("========================url:{}",LIST_TIME_API);
                log.info("========================response:{}",objectMap);
                return OBJECT_MAPPER.writeValueAsString(objectMap);
            }
        } catch (Exception e) {
            log.error("execute error.",e);
        }

        return "";
    }
}
